package com.zero2oneit.mall.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zero2oneit.mall.common.bean.member.CouponRule;
import com.zero2oneit.mall.common.bean.member.MemberCoupon;
import com.zero2oneit.mall.common.query.member.MemberCouponQueryObject;
import com.zero2oneit.mall.common.utils.R;
import com.zero2oneit.mall.common.utils.bootstrap.BoostrapDataGrid;
import com.zero2oneit.mall.member.service.CouponRuleService;
import com.zero2oneit.mall.member.service.MemberInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.zero2oneit.mall.member.mapper.MemberCouponMapper;
import com.zero2oneit.mall.member.service.MemberCouponService;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;

/**
 * Description:
 *
 * @author Tg
 * @email zero2oneit@163.com
 * @date 2021-05-23
 */
@Service
public class MemberCouponServiceImpl extends ServiceImpl<MemberCouponMapper, MemberCoupon> implements MemberCouponService {

    @Autowired
    private MemberCouponMapper memberCouponMapper;

    @Autowired
    private MemberInfoService memberService;

    @Autowired
    private CouponRuleService couponRuleService;

    @Override
    public BoostrapDataGrid pageList(MemberCouponQueryObject qo) {
        //查询总记录数
        int total = memberCouponMapper.selectTotal(qo);
        return new BoostrapDataGrid(total, total == 0 ? Collections.EMPTY_LIST : memberCouponMapper.selectRows(qo));
    }

    @Override
    public R load(MemberCouponQueryObject qo) {
        List<HashMap<String,Object>> list = memberCouponMapper.load(qo);
        return R.ok(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R receive(MemberCouponQueryObject qo) {
        QueryWrapper<CouponRule> wrapper = new QueryWrapper();
        wrapper.eq("id", qo.getMemberId());
        CouponRule couponRule = couponRuleService.getById(qo.getCouponId());
        if (couponRule.getCouponCount() > 0){
            //减少库存
            couponRuleService.reduce(qo);
            //领取优惠券
            memberService.coupon(qo.getMemberId(), qo.getCouponId());
        }
        return R.ok();
    }

    @Override
    public void status(String id, Integer status) {
        memberCouponMapper.status(Long.parseLong(id), status);
    }

}